package cn.tonyandmoney.voicenotes.notes.presenter.impl

import android.content.Context
import cn.tonyandmoney.voicenotes.notes.bean.PageEntity
import cn.tonyandmoney.voicenotes.notes.entity.TNote
import cn.tonyandmoney.voicenotes.notes.model.NoteModel
import cn.tonyandmoney.voicenotes.notes.presenter.INoteListPresenter
import cn.tonyandmoney.voicenotes.notes.presenter.INoteListView
import com.dhh.rxlifecycle2.RxLifecycle
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.error
import org.jetbrains.anko.info

/**
 * 所以获取我的笔记信息记录
 */
class NotesListPresenter(private val mView: INoteListView,
                         private val mContext: Context) : INoteListPresenter, AnkoLogger,
        SearchPresenter(mContext, mView) {

    companion object {
        private const val TAG = "ErrorConsumer"

    }

    private val mModel = NoteModel()

    override fun queryData(refresh: Boolean, offset: Int, keywords: String?) {
        Observable.create<PageEntity<TNote>> {
            it.onNext(mModel.query(offset, 15, keywords))
            it.onComplete()
        }.compose(RxLifecycle.with(mContext).bindOnDestroy())
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer {
                    if (refresh) {
                        mView.setData(it.page, it.canLoadMore())
                    } else {
                        mView.addData(it.page, it.canLoadMore())
                    }
                }, ErrorConsumer())
    }

    override fun loadTypes(): List<String> = mModel.loadTypes()

    override fun delete(note: TNote) = mModel.delete(note)

    override fun searchByType(refresh: Boolean, offset: Int, types: List<String>) {
        info("searchByType->$types")
        Observable.create<PageEntity<TNote>> {
            it.onNext(mModel.query(offset, 15, types))
            it.onComplete()
        }.compose(RxLifecycle.with(mContext).bindOnDestroy())
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer {
                    if (refresh) {
                        mView.setData(it.page, it.canLoadMore())
                    } else {
                        mView.addData(it.page, it.canLoadMore())
                    }
                }, ErrorConsumer())
    }


    inner class ErrorConsumer : Consumer<Throwable> {
        override fun accept(t: Throwable?) {
            error("$TAG: $t")
            mView.addData(emptyList(), true)
            mView.showAlert("加载失败，请重试。")
        }
    }
}